import $ from 'jquery';//一個user類，一個全局變量

export default{
    state : {
        id: "",
        username : "",
        photo : "",
        token: "",
        is_login: false,
        pulling_info : true,//判斷是否正在服務器拉取信息。
    },
    getters: {
    },
    mutations: {

        updateUser(state,user){
            state.id = user.id;
            state.username = user.username;
            state.photo = user.photo;
            state.is_login = user.is_login;

        },

        updatetoken(state,token){
            state.token = token;
        },
        logout(state){
            state.id = "";
            state.username = "";
            state.photo = "";
            state.token = "";
            state.is_login = false;
        },

        updatePullinginfo(state,logo){
            state.pulling_info = logo;
        }
    },
    actions: {
        login(contetx,data){//这里的context只用来启动muta里的函数

            $.ajax({
                type: "post",
                url: "https://app5541.acapp.acwing.com.cn/api/user/account/token/",
                data: {
                username:data.username,
                password:data.password,
                },
                success(resp) {
                    if(resp.error_message === "success"){//如果成功了
                        localStorage.setItem("jwt_token",resp.token);
                        contetx.commit("updatetoken",resp.token)
                        data.success(resp);
                    }else {
                        data.error(resp);
                    }
                },
                error(resp){
                data.error(resp);
                }
            });
        },

        getinfo(context,data){
            $.ajax({
                url:"https://app5541.acapp.acwing.com.cn/api/user/account/info/",
                type:"get",
                headers:{
                  Authorization: "Bearer " + context.state.token//授权
                },
                success(resp){
                    if(resp.error_message === "success"){
                        context.commit("updateUser",{
                            ...resp,
                            is_login:true,
                          })
        
                          data.success(resp);
                    }
                    else{
                        data.error(resp);
                    }
                  
                },
                error(resp){
                  data.error(resp);
                }
            })
        },
        logout(context){
            localStorage.removeItem("jwt_token");
            context.commit("logout");
        }
    },
    modules: {
    }
}